package com.huiquan.medicine.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.medicine.dao.DrugDao;
import com.huiquan.medicine.entity.BasDrug;

/**
 * 药品 service
 *
 * @author leo
 * @time 2017年4月5日 下午5:27:14
 */
@Service
public class DrugService extends BaseService {
	/** 疾病图片的虚拟路径 */
	public static final String ORIGINAL_IMAGE_PATH = "/home/analysis/images/drug_image/original/";
	public static final String THUMBNAIL_IMAGE_PATH = "/home/analysis/images/drug_image/thumbnail/";
	@Autowired
	private DrugDao drugDao;

	/**
	 * 获取疾病图片列表
	 * 
	 * @param start
	 * @param keyword
	 * @return
	 */
	public Map<String, Object> getList(String startStr, String keyword,String exactSearchFlag,String countPerPageStr) {
		int start = startStr == null ? 1 : Integer.parseInt(startStr);
		Map<String, Object> param = new HashMap<>();
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		if (keyword != null && !keyword.isEmpty()) {
			param.put("drugName",exactFlag ? keyword : "%" + keyword + "%");
		}
		int totalSize = drugDao.retrieveSize(param);

		Map<String, Integer> pageNo ;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<BasDrug> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = drugDao.retrieveList(param);
		}
		//分隔符
		char flag = 1;
		for(BasDrug bd :list){
			String in = bd.getImgName();
			String [] ins =  in.split("\\"+flag);
			StringBuffer names = new StringBuffer();
			for(String n : ins){
				names.append(n).append("&nbsp;&nbsp;&nbsp;");
			}
			bd.setImgName(names.toString());
		}
		
		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("codeSearch", "药品名称");
		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("codeSearch", keyword);
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("exactSearchFlag", exactSearchFlag);
		return map;
	}

	public Map<String, Object> preEdit(String codeSearch, String nameSearch, String categorySearch, String id,
			User user, String exactSearchFlag, String modifyFlag) {
		// 如果id不为空则表示是修改，否则为新增
		Map<String, Object> map = new HashMap<>();
		if (id != null && !id.isEmpty()) {
			BasDrug drug = drugDao.retrieveObjectById(Long.parseLong(id));
			map.put("produceAddr", drug.getProduceAddr());
			map.put("approvalDoc", drug.getApprovalDoc());
			map.put("prescriptionFlag", drug.getPrescriptionFlag());
			map.put("supportInsurance", drug.getSupportInsurance());
			map.put("sfxy", drug.getSfxy());
			map.put("drugName", drug.getDrugName());
			map.put("component", drug.getComponent());
			map.put("indFun", drug.getIndFun());
			map.put("specification", drug.getSpecification());
			map.put("drugUsage", drug.getDrugUsage());
			map.put("adverseEffect", drug.getAdverseEffect());
			map.put("specialUse", drug.getSpecialUse());
			map.put("taboo", drug.getTaboo());
			map.put("drugInteraction", drug.getDrugInteraction());
			map.put("yfyy", drug.getYfyy());
			map.put("etyy", drug.getEtyy());
			map.put("lnyy", drug.getLnyy());
			map.put("syrq", drug.getSyrq());
			map.put("price", drug.getPrice());
			map.put("status", drug.getStatus());
			map.put("buyFlag", drug.getBuyFlag());
			map.put("buyCity", drug.getBuyCity());
			map.put("pharmacyId", drug.getPharmacyId());
			char flag = 1;
			String name = drug.getImgName();
			if(StringUtils.isNotBlank(name)){
				String[] images = drug.getImgName().split(flag+"");
				String[] imageUrls = drug.getImgUrl().split(flag+"");
				List<Map<String, String> > image = new ArrayList<>();
				for(String img:images){
					if(StringUtils.isNotBlank(img)){
						Map<String, String> maps = new HashMap<>();
						for(String imgUrl :imageUrls){
							if(imgUrl.contains(img)){
								maps.put("url", imgUrl);
								maps.put("img", img);
								image.add(maps);
							}
						}
					}
				}
				map.put("images", image);
			}
		}

		
		map.put("id", id);
		map.put("codeSearch", codeSearch);
		map.put("nameSearch", nameSearch);
		map.put("categorySearch", categorySearch);
		map.put("exactSearchFlag", exactSearchFlag);
		map.put("modifyFlag", modifyFlag);

		return map;
	}

	/** 上传图片保存路径 */
	@Value("${drug.image.original.path}")
	private String uploadOriginalImagePath;
	@Value("${drug.image.thumbnail.path}")
	private String uploadThumbnailImagePath;
	public ReturnData addDrug(Map<String , String > params , User user,Map<String , MultipartFile> fileMap) throws IllegalStateException, IOException{
		BasDrug bd = new BasDrug();
		 bd = getDrug(params,bd);
		int count = Integer.parseInt(params.get("count"));
		//原图名称
		List<String > imageNames = new ArrayList<>();
		for(int i = 1; i<=count;i++){
			//原图和缩图
			MultipartFile orFile = fileMap.get("orImage_"+i);
			MultipartFile thFile = fileMap.get("thImage_"+i);
			//上传服务器
			String imageName = orFile.getOriginalFilename();
			int drCount = drugDao.retrieveSizeByName(imageName);
			if(drCount>0){
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("图片名字已经存在");
				return ReturnUtil.fail(rc);
			}
			imageNames.add(imageName);
			uploadImage(orFile, uploadOriginalImagePath, imageName, ORIGINAL_IMAGE_PATH);
			//保存缩图时名称:"thumbnail"+名称
			uploadImage(thFile, uploadThumbnailImagePath, "thumbnail"+imageName, THUMBNAIL_IMAGE_PATH);
		}
		//保存名称和url 只保存原图的URL和名称用char=1分割
		//分隔符
		char flag = 1;
		StringBuffer imgName = new StringBuffer();
		StringBuffer imgUrl = new  StringBuffer();
		for(String imageName:imageNames){
			imgName.append(imageName).append(flag);
			imgUrl.append(ORIGINAL_IMAGE_PATH).append(imageName).append(flag);
		}
		if(imgName.length()>0){
			bd.setImgName(imgName.toString().substring(0, imgName.length()-1));
		}else{
			bd.setImgName("");
		}
		if(imgUrl.length()>0){
			bd.setImgUrl(imgUrl.toString().substring(0, imgUrl.length()-1));
		}else{
			bd.setImgUrl("");
		}
		drugDao.insert(bd);
		return ReturnUtil.success();
	}
	
	public ReturnData updateDrug(Map<String , String > params , User user,Map<String , MultipartFile> fileMap,String id) throws IllegalStateException, IOException{
		BasDrug bd = drugDao.retrieveObjectById(Long.parseLong(id));
		bd = getDrug(params, bd);
		int count = Integer.parseInt(params.get("count"));
		//原图名称
		List<String > imageNames = new ArrayList<>();
		for(int i = 1; i<=count;i++){
			//原图和缩图
			MultipartFile orFile = fileMap.get("orImage_"+i);
			MultipartFile thFile = fileMap.get("thImage_"+i);
			//上传服务器
			String imageName = orFile.getOriginalFilename();
			int drCount = drugDao.retrieveSizeByName(imageName);
			if(drCount>0){
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("图片名字已经存在");
				return ReturnUtil.fail(rc);
			}
			imageNames.add(imageName);
			uploadImage(orFile, uploadOriginalImagePath, imageName, ORIGINAL_IMAGE_PATH);
			//保存缩图时名称:"thumbnail"+名称
			uploadImage(thFile, uploadThumbnailImagePath, "thumbnail"+imageName, THUMBNAIL_IMAGE_PATH);
		}
		//保存名称和url 只保存原图的URL和名称用char=1分割
		//分隔符
		char flag = 1;
		StringBuffer imgName = new StringBuffer();
		StringBuffer imgUrl = new  StringBuffer();
		if(StringUtils.isNotBlank(bd.getImgName())){
			imgName.append(bd.getImgName()).append(flag);
		}
		if(StringUtils.isNotBlank(bd.getImgUrl())){
			imgUrl.append(bd.getImgUrl()).append(flag);
		}
		for(String imageName:imageNames){
			imgName.append(imageName).append(flag);
			imgUrl.append(ORIGINAL_IMAGE_PATH).append(imageName).append(flag);
		}
		bd.setImgName(imgName.toString().substring(0, imgName.length()-1));
		bd.setImgUrl(imgUrl.toString().substring(0, imgUrl.length()-1));
		drugDao.update(bd);
		return ReturnUtil.success();
	}
	
	public ReturnData deleteImage(String id ,String imageName,User user ) throws IllegalStateException, IOException{
		BasDrug bd = drugDao.retrieveObjectById(Long.parseLong(id));
		String images = bd.getImgName();
		String url = bd.getImgUrl();
		
		//分割符
		char flag= 1;
		String[] imageNames = images.split(flag+"");
		StringBuffer newName = new StringBuffer();
		for(String n:imageNames){
			if(!StringUtils.equalsIgnoreCase(imageName, n)){
				newName.append(n).append(flag);
			}
		}
		if(newName.length()>0){
			bd.setImgName(newName.toString().substring(0,newName.length()-1));
		}else{
			bd.setImgName("");
		}
		
		String[] urls = url.split(flag+"");
		StringBuffer newUrl = new StringBuffer();
		for(String u:urls){
			if(!u.contains(imageName)){
				newUrl.append(u).append(flag);
			}
		}
		if(newUrl.length()>0){
			bd.setImgUrl(newUrl.toString().substring(0,newUrl.length()-1));
		}else{
			bd.setImgUrl("");
		}
		drugDao.update(bd);
		return ReturnUtil.success();
	}
	public ReturnData deleteDrug(String id ) throws IllegalStateException{
		drugDao.deleteById(id);
		return ReturnUtil.success();
	}
	private BasDrug getDrug (Map<String, String > params,BasDrug bd){
		bd.setProduceAddr(params.get("produceAddr"));
		bd.setApprovalDoc(params.get("approvalDoc"));
		bd.setPrescriptionFlag(Integer.parseInt(params.get("prescriptionFlag")));
		bd.setSupportInsurance(Integer.parseInt(params.get("supportInsurance")));
		bd.setSfxy(Integer.parseInt(params.get("sfxy")));
		bd.setDrugName(params.get("drugName"));
		bd.setComponent(params.get("component"));
		bd.setIndFun(params.get("indFun"));
		bd.setSpecification(params.get("specification"));
		bd.setDrugUsage(params.get("drugUsage"));
		bd.setAdverseEffect(params.get("adverseEffect"));
		bd.setSpecialUse(params.get("specialUse"));
		bd.setTaboo(params.get("taboo"));
		bd.setDrugInteraction(params.get("drugInteraction"));
		bd.setYfyy(params.get("yfyy"));
		bd.setEtyy(params.get("etyy"));
		bd.setLnyy(params.get("lnyy"));
		bd.setSyrq(params.get("syrq"));
		bd.setPrice(params.get("price"));
		bd.setStatus(params.get("status"));
		bd.setBuyFlag(params.get("buyFlag"));
		bd.setBuyCity(params.get("buyCity"));
		bd.setPharmacyId(params.get("pharmacyId"));
		
		return bd;
		
		
	}

	/**
	 * 上传图片到服务器
	 * 
	 * @param image
	 *            图片文件流
	 * @param imageName
	 *            图片名
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	private String uploadImage(MultipartFile image,String imagePath, String imageName,String paths) throws IllegalStateException, IOException {
		String path = imagePath + imageName;
		File file = new File(path);
		image.transferTo(file);
		return paths + imageName;
	}

}
